package com.qms.qep.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.qms.common.annotation.Log;
import com.qms.common.config.RuoYiConfig;
import com.qms.common.core.controller.BaseController;
import com.qms.common.core.domain.AjaxResult;
import com.qms.common.core.page.TableDataInfo;
import com.qms.common.enums.BusinessType;
import com.qms.qep.domain.CertificateTemplate;
import com.qms.qep.domain.TemplateVariable;
import com.qms.qep.service.ICertificateTemplateService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 证书模板管理 控制器
 */
@Api(tags = "证书模板管理")
@RestController
@RequestMapping("/qep/certificate/template")
public class CertificateTemplateController extends BaseController {
    
    private static final Logger log = LoggerFactory.getLogger(CertificateTemplateController.class);
    
    @Autowired
    private ICertificateTemplateService certificateTemplateService;

    /**
     * 获取证书模板列表
     */
    @ApiOperation("获取证书模板列表")
    @PreAuthorize("@ss.hasPermi('qep:certificate:template:list')")
    @GetMapping("/list")
    public TableDataInfo list(CertificateTemplate template) {
        startPage();
        List<CertificateTemplate> list = certificateTemplateService.selectCertificateTemplateList(template);
        return getDataTable(list);
    }

    /**
     * 获取证书模板详细信息
     */
    @ApiOperation("获取证书模板详细信息")
    @PreAuthorize("@ss.hasPermi('qep:certificate:template:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        CertificateTemplate template = certificateTemplateService.selectCertificateTemplateById(id);
        return success(template);
    }

    /**
     * 新增证书模板
     */
    @ApiOperation("新增证书模板")
    @PreAuthorize("@ss.hasPermi('qep:certificate:template:add')")
    @Log(title = "证书模板管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CertificateTemplate template) {
        return toAjax(certificateTemplateService.insertCertificateTemplate(template));
    }

    /**
     * 修改证书模板
     */
    @ApiOperation("修改证书模板")
    @PreAuthorize("@ss.hasPermi('qep:certificate:template:edit')")
    @Log(title = "证书模板管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CertificateTemplate template) {
        return toAjax(certificateTemplateService.updateCertificateTemplate(template));
    }

    /**
     * 删除证书模板
     */
    @ApiOperation("删除证书模板")
    @PreAuthorize("@ss.hasPermi('qep:certificate:template:remove')")
    @Log(title = "证书模板管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(certificateTemplateService.deleteCertificateTemplateByIds(ids));
    }
    
    /**
     * 上传证书模板文件
     */
    @ApiOperation("上传证书模板文件")
    @PreAuthorize("@ss.hasPermi('qep:certificate:template:upload')")
    @Log(title = "证书模板管理", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file, 
                             @RequestParam(value = "name", required = false) String name,
                             @RequestParam(value = "type", required = false) String type,
                             @RequestParam(value = "remark", required = false) String remark) {
        if (file.isEmpty()) {
            return error("上传文件不能为空");
        }
        
        return certificateTemplateService.uploadTemplateFile(file, name, type, remark);
    }
    
    /**
     * 预览证书模板
     */
    @ApiOperation("预览证书模板")
    @PreAuthorize("@ss.hasPermi('qep:certificate:template:query')")
    @GetMapping("/preview/{id}")
    public AjaxResult preview(@PathVariable("id") Long id) {
        try {
            CertificateTemplate template = certificateTemplateService.selectCertificateTemplateById(id);
            if (template == null) {
                return error("模板不存在");
            }

            if ("DOCX".equals(template.getTemplateFormat())) {
                if (StringUtils.isEmpty(template.getTemplateFileUrl())) {
                    return error("DOCX模板文件URL未配置，无法预览");
                }
                String htmlContent = certificateTemplateService.previewDocxAsHtml(id);
                return success(htmlContent);
            } else if ("HTML".equals(template.getTemplateFormat())) {
                String contentToPreview = StringUtils.hasText(template.getEditorContent()) 
                                        ? template.getEditorContent() 
                                        : template.getContent();
                return success(contentToPreview);
            } else {
                return error("不支持预览此模板格式: " + template.getTemplateFormat());
            }
        } catch (Exception e) {
            log.error("预览模板失败, ID: {}", id, e);
            return error("预览失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取模板变量列表
     */
    @ApiOperation("获取模板变量列表")
    @PreAuthorize("@ss.hasPermi('qep:certificate:template:query')")
    @GetMapping("/variables/{templateId}")
    public AjaxResult getVariables(@PathVariable("templateId") Long templateId) {
        List<TemplateVariable> variables = certificateTemplateService.selectTemplateVariables(templateId);
        return success(variables);
    }
    
    /**
     * 保存模板变量
     */
    @ApiOperation("保存模板变量")
    @PreAuthorize("@ss.hasPermi('qep:certificate:template:edit')")
    @Log(title = "证书模板变量", businessType = BusinessType.UPDATE)
    @PostMapping("/variables")
    public AjaxResult saveVariables(@RequestBody List<TemplateVariable> variables) {
        return toAjax(certificateTemplateService.saveTemplateVariables(variables));
    }
    
    /**
     * 获取Word模板内容
     */
    @ApiOperation("获取Word模板内容")
    @PreAuthorize("@ss.hasPermi('qep:certificate:template:query')")
    @GetMapping("/word-content/{id}")
    public AjaxResult getWordContent(@PathVariable("id") Long id) {
        return certificateTemplateService.getWordContent(id);
    }
    
    /**
     * 保存Word模板内容
     */
    @ApiOperation("保存Word模板内容")
    @PreAuthorize("@ss.hasPermi('qep:certificate:template:edit')")
    @Log(title = "证书模板管理", businessType = BusinessType.UPDATE)
    @PostMapping("/word-content")
    public AjaxResult saveWordContent(@RequestBody CertificateTemplate template) {
        return certificateTemplateService.saveWordContent(template);
    }

    /**
     * 导出PDF
     */
    @ApiOperation("导出PDF")
    @PreAuthorize("@ss.hasPermi('qep:certificate:template:export')")
    @Log(title = "证书模板管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export-pdf/{id}")
    public ResponseEntity<byte[]> exportPdf(@PathVariable("id") Long id, @RequestBody Map<String, Object> variables) {
        AjaxResult result = certificateTemplateService.exportToPdf(id, variables);
        
        if (result.isSuccess()) {
            byte[] pdfBytes = (byte[]) result.get("data");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_PDF);
            headers.setContentDispositionFormData("attachment", "certificate_" + id + ".pdf");
            
            return new ResponseEntity<>(pdfBytes, headers, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 解析Word文档
     */
    @ApiOperation("解析Word文档")
    @PreAuthorize("@ss.hasPermi('qep:certificate:template:edit')")
    @PostMapping("/parse-word")
    public AjaxResult parseWord(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return error("上传文件不能为空");
        }
        
        // 检查文件类型
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || (!originalFilename.toLowerCase().endsWith(".docx") && !originalFilename.toLowerCase().endsWith(".doc"))) {
            return error("只支持Word文档(doc, docx)格式");
        }
        
        try {
            // 使用现有服务或创建新方法进行Word转HTML处理
            String htmlContent = certificateTemplateService.parseWordToHtml(file);
            return success(htmlContent);
        } catch (Exception e) {
            log.error("Word文档解析失败", e);
            return error("Word文档解析失败: " + e.getMessage());
        }
    }
    
    /**
     * 解析Excel文档
     */
    @ApiOperation("解析Excel文档")
    @PreAuthorize("@ss.hasPermi('qep:certificate:template:edit')")
    @PostMapping("/parse-excel")
    public AjaxResult parseExcel(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return error("上传文件不能为空");
        }
        
        // 检查文件类型
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || (!originalFilename.toLowerCase().endsWith(".xlsx") && !originalFilename.toLowerCase().endsWith(".xls"))) {
            return error("只支持Excel文档(xls, xlsx)格式");
        }
        
        try {
            // 使用现有服务或创建新方法进行Excel转HTML处理
            String htmlContent = certificateTemplateService.parseExcelToHtml(file);
            return success(htmlContent);
        } catch (Exception e) {
            log.error("Excel文档解析失败", e);
            return error("Excel文档解析失败: " + e.getMessage());
        }
    }
    
    /**
     * 解析PowerPoint文档
     */
    @ApiOperation("解析PowerPoint文档")
    @PreAuthorize("@ss.hasPermi('qep:certificate:template:edit')")
    @PostMapping("/parse-ppt")
    public AjaxResult parsePpt(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return error("上传文件不能为空");
        }
        
        // 检查文件类型
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || (!originalFilename.toLowerCase().endsWith(".pptx") && !originalFilename.toLowerCase().endsWith(".ppt"))) {
            return error("只支持PowerPoint文档(ppt, pptx)格式");
        }
        
        try {
            // 使用现有服务或创建新方法进行PPT转HTML处理
            String htmlContent = certificateTemplateService.parsePptToHtml(file);
            return success(htmlContent);
        } catch (Exception e) {
            log.error("PowerPoint文档解析失败", e);
            return error("PowerPoint文档解析失败: " + e.getMessage());
        }
    }
    
    /**
     * 解析PDF文档
     */
    @ApiOperation("解析PDF文档")
    @PreAuthorize("@ss.hasPermi('qep:certificate:template:edit')")
    @PostMapping("/parse-pdf")
    public AjaxResult parsePdf(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return error("上传文件不能为空");
        }
        
        // 检查文件类型
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || !originalFilename.toLowerCase().endsWith(".pdf")) {
            return error("只支持PDF文档格式");
        }
        
        try {
            // 使用现有服务或创建新方法进行PDF转HTML处理
            String htmlContent = certificateTemplateService.parsePdfToHtml(file);
            return success(htmlContent);
        } catch (Exception e) {
            log.error("PDF文档解析失败", e);
            return error("PDF文档解析失败: " + e.getMessage());
        }
    }

    /**
     * 上传并替换DOCX模板文件
     */
    @ApiOperation("上传并替换DOCX模板文件")
    @PreAuthorize("@ss.hasPermi('qep:certificate:template:edit')")
    @Log(title = "证书模板管理", businessType = BusinessType.UPDATE)
    @PostMapping("/replace-docx")
    public AjaxResult replaceDocx(@RequestParam("templateId") Long templateId, 
                                  @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return error("上传文件不能为空");
        }
        
        // 校验文件类型是否为DOCX
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || !originalFilename.toLowerCase().endsWith(".docx")) {
            return error("只支持Word文档(docx)格式");
        }

        try {
            return certificateTemplateService.replaceDocxTemplate(templateId, file);
        } catch (IOException e) {
            log.error("替换DOCX模板文件失败, TemplateID: {}", templateId, e);
            return error("文件处理失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("替换DOCX模板文件时发生未知错误, TemplateID: {}", templateId, e);
            return error("替换失败: " + e.getMessage());
        }
    }

    /**
     * 下载模板文件
     */
    @ApiOperation("下载模板文件")
    @PreAuthorize("@ss.hasPermi('qep:certificate:template:query')")
    @GetMapping("/download/{id}")
    public ResponseEntity<byte[]> downloadTemplate(@PathVariable("id") Long id) {
        try {
            CertificateTemplate template = certificateTemplateService.selectCertificateTemplateById(id);
            if (template == null) {
                log.error("下载模板文件失败: 模板不存在, ID: {}", id);
                return ResponseEntity.notFound().build();
            }

            if (StringUtils.isEmpty(template.getTemplateFileUrl())) {
                log.error("下载模板文件失败: 模板文件URL为空, ID: {}", id);
                return ResponseEntity.notFound().build();
            }

            // 获取基础路径
            String basePath = RuoYiConfig.getProfile();
            log.info("文件基础路径: {}", basePath);

            // 获取模板路径
            String templatePath = template.getTemplateFileUrl();
            log.info("数据库中的模板路径: {}", templatePath);

            // 构建完整文件路径
            String fullPath = basePath + "/" + templatePath;
            // 确保路径中没有重复的斜杠
            fullPath = fullPath.replace("//", "/");
            
            log.info("尝试从路径下载文件: {}", fullPath);
            
            // 调用服务层方法获取文件字节
            byte[] fileContent = certificateTemplateService.getTemplateFileContent(fullPath);
            if (fileContent == null || fileContent.length == 0) {
                log.error("下载模板文件失败: 文件不存在或为空, 路径: {}", fullPath);
                return ResponseEntity.notFound().build();
            }

            // 提取文件名
            String filename = templatePath;
            if (templatePath.contains("/")) {
                filename = templatePath.substring(templatePath.lastIndexOf('/') + 1);
            }
            
            // 如果文件名不包含扩展名，添加.docx
            if (!filename.toLowerCase().endsWith(".docx")) {
                filename += ".docx";
            }

            // 设置HTTP头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", filename);
            
            log.info("下载模板文件成功: {}, 大小: {} 字节", filename, fileContent.length);
            
            return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
        } catch (Exception e) {
            log.error("下载模板文件失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 测试文件访问
     */
    @ApiOperation("测试文件访问")
    @GetMapping("/test-file")
    public ResponseEntity<byte[]> testFileAccess() {
        log.info("测试文件访问");
        try {
            // 获取基础路径
            String basePath = RuoYiConfig.getProfile();
            log.info("文件基础路径: {}", basePath);
            
            // 使用测试文本文件
            String testFilePath = basePath + "/certificate_templates/test_file.txt";
            log.info("尝试加载测试文件: {}", testFilePath);
            
            java.io.File testFile = new java.io.File(testFilePath);
            log.info("文件存在: {}, 是文件: {}, 大小: {} 字节", 
                testFile.exists(), testFile.exists() && testFile.isFile(), 
                testFile.exists() ? testFile.length() : 0);
            
            if (!testFile.exists() || !testFile.isFile()) {
                log.error("测试文件不存在或不是文件: {}", testFilePath);
                return ResponseEntity.notFound().build();
            }
            
            // 读取文件内容
            byte[] fileContent = java.nio.file.Files.readAllBytes(testFile.toPath());
            log.info("成功读取文件内容，大小: {} 字节", fileContent.length);
            
            if (fileContent.length == 0) {
                log.error("文件内容为空: {}", testFilePath);
                return ResponseEntity.noContent().build();
            }
            
            // 设置HTTP头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.TEXT_PLAIN);
            headers.setContentDispositionFormData("attachment", "test_file.txt");
            
            // 记录成功消息
            log.info("成功构建下载响应，内容大小: {} 字节", fileContent.length);
            
            // 返回文件内容
            return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
        } catch (Exception e) {
            log.error("测试文件访问失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
} 